﻿using DDBS_Server.Models;
using Raven.Abstractions.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace DDBS_Server.ViewControllers
{
    [Authorize]
    public class SamplesController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "You can search for similar samples in known databases from here.";
            return View();
        }

        [Route("Samples/Chart/{i:int}")]
        [HttpGet]
        public ActionResult Chart(int i)
        {
            Sample simSample = TempData["simSample"] as Sample;
            List<Sample> results = TempData["results"] as List<Sample>;
            var chart = TempData["chart"];

            ViewBag.chart = chart;
            ViewBag.theme = ChartTheme.Blue;
            ViewBag.simSample = simSample;
            ViewBag.resSample = results[i];

            //store for next read
            TempData["simSample"] = simSample;
            TempData["results"] = results;
            TempData["chart"] = chart;

            return View();
        }

        [Route("Samples/Sample/{shard}/{doc}/{id}/{sel:int}")]
        [HttpGet]
        public FileResult DlSample(string shard, string doc, string id, int sel)
        {
            string sid;
            if(sel == 0) sid = String.Concat(doc, "/", id);
            else sid = String.Concat(shard, "/", doc, "/", id);
            APIControllers.RavenDB DB = new APIControllers.RavenDB(shard);
            Sample s = DB.GetSampleByID(sid);
            Attachment atch = DB.GetSampleAtch(sid);

            //var result = new FileContentResult(StreamToArray(atch.Data()), atch.Metadata["Content-Type"].ToString());
            var result = new FileContentResult(StreamToArray(atch.Data()), "text");
            result.FileDownloadName = s.Name + ".txt";
            return result;
        }

        private byte[] StreamToArray(Stream stream)
        {
            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }

        [Route("Samples/getsamplesbtp")]
        [HttpPost]
        public ActionResult GetSamples(HttpPostedFileBase file, double? tolerance, float? rtolerance, string chart)
        {
            ViewBag.Message = "You can search for similar samples in known databases from here.";

            if (file == null)
            {
                ViewBag.Error = "File missing.";
                return View("Index");
            }
            if (tolerance == null) tolerance = 0;
            if (rtolerance == null) rtolerance = 0;

            //simSample
            Sample simSample = simSampleLoad(file);
            ViewBag.simSample = simSample;

            //results
            APIControllers.RavenDB DB = new APIControllers.RavenDB();
            List<Sample> results = DB.GetSamplesByTopPeaks(simSample, (double)tolerance, (float)rtolerance);
            foreach (Sample s in results)
            {
                if (s.Id.Count(c => c == '/') < 2) s.Id = String.Concat(s.Shard, "/", s.Id, "/", 0);
                else s.Id += "/1";
            }
            List<string> sids = results.Select(s => s.Id).ToList();
            ViewBag.sids = sids;
            ViewBag.resCount = results.Count;

            //for Chart() action
            TempData["simSample"] = simSample;
            TempData["chart"] = chart;
            TempData["results"] = results;

            return View("Index");
        }

        private Sample simSampleLoad(HttpPostedFileBase file)
        {
            Sample simSample = new Sample("simSample");
            try
            {
                StreamReader streamReader = new StreamReader(file.InputStream);
                string filecontent = streamReader.ReadToEnd();
                streamReader.Close();

                simSample.PeaksFromCSV(filecontent);
                return simSample;
            }
            catch (Exception e)
            {
                ViewBag.Error = "Cannot parse file.";
                ViewBag.ErrorDetail = e.ToString();
                return null;
            }
        }

    }
}